<script setup>
import { use } from 'echarts/core'
import { SankeyChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { ref, watch } from 'vue'

use([SankeyChart, TitleComponent, TooltipComponent])

const props = defineProps({
  data: {
    type: Object,
    required: true
  },
  title: {
    type: String,
    default: ''
  },
  height: {
    type: String,
    default: '600px'
  }
})

const option = ref({
  title: {
    text: props.title,
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    triggerOn: 'mousemove'
  },
  series: [
    {
      type: 'sankey',
      data: props.data.nodes,
      links: props.data.links,
      emphasis: {
        focus: 'adjacency'
      },
      levels: [
        {
          depth: 0,
          itemStyle: {
            color: '#fbb4ae'
          },
          lineStyle: {
            color: 'source',
            opacity: 0.6
          }
        },
        {
          depth: 1,
          itemStyle: {
            color: '#b3cde3'
          },
          lineStyle: {
            color: 'source',
            opacity: 0.6
          }
        },
        {
          depth: 2,
          itemStyle: {
            color: '#ccebc5'
          },
          lineStyle: {
            color: 'source',
            opacity: 0.6
          }
        }
      ],
      lineStyle: {
        curveness: 0.5
      }
    }
  ]
})

watch(() => props.data, (newVal) => {
  option.value.series[0].data = newVal.nodes
  option.value.series[0].links = newVal.links
}, { deep: true })

watch(() => props.title, (newVal) => {
  option.value.title.text = newVal
})
</script>

<template>
  <v-chart class="chart" :option="option" :style="{ height }" />
</template>

<style scoped>
.chart {
  width: 100%;
}
</style>